﻿using System.ComponentModel.DataAnnotations;

namespace StarsAdmin.Core.Attributes
{
    /// <summary>
    /// 自定义的集合验证标记
    /// 支持验证 "对象集合" 和 "long类型集合"
    /// </summary>
    public class NotEmptyCollectionAttribute : ValidationAttribute
    {
        protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
        {
            if (value is System.Collections.IEnumerable enumerable)
            {
                var enumerator = enumerable.GetEnumerator();
                if (!enumerator.MoveNext())
                {
                    return new ValidationResult(ErrorMessage ?? "集合不能为空。");
                } else
                {
                    foreach (var item in enumerable)
                    {
                        if (item is long && item.ToString() == "0")
                        {
                            return new ValidationResult(ErrorMessage ?? "集合不能为空。");
                        }
                    }
                }
            }

            return ValidationResult.Success;
        }
    }
}